package interceptor;

import java.util.Locale;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.CookiesAware;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 拦截器，拦截所有的action请求。主要是用于，用户在进入游戏页面时，获得用户
 * 登录的信息。 放在session中。
 *
 * @author Administrator
 *
 */

public class I18nInterceptor extends AbstractInterceptor{


	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		ActionContext con = invocation.getInvocationContext();
		System.out.println(con);
		Map<String,Object> session =  con.getSession();
		Cookie[] cookies = ServletActionContext.getRequest().getCookies();
		System.out.println(cookies);
		
		boolean login = false;
		
		if(cookies != null){
		for(Cookie cookie:cookies){
			if(cookie.getName().equals("username")){
				String name = cookie.getValue();
				session.put("username", name.replace('+', ' '));
				System.out.println(session);
				System.out.println("用户已登录：" + name);
				login = true;
			}
//			else{
//				session.remove("username");
//				session.put("userip", ServletActionContext.getRequest().getRemoteAddr());
//			}
			
		}
		}
		
		
//		System.out.println(cookie);
//		
//		if(cookie.get("username") != null){
//			session.put("username", cookie.get("username"));
//			session.put("userid", cookie.get("userid"));
//			System.out.println(cookie.get("userid"));
//		}
		
		System.out.println("language_code:"+session.get("language_code"));
		
		if(session.get("language_code") != null){
			System.out.println("test pre:");
			con.setLocale(new Locale((String) session.get("language_code")));
			session.put("WW_TRANS_I18N_LOCALE", (String) session.get("language_code"));
		}

		System.out.println("CookieInterceptor 执行前");
		String result =  invocation.invoke();
		if(session.get("language_code") != null){
			System.out.println("test after:");
			con.setLocale(new Locale((String) session.get("language_code")));
			session.put("WW_TRANS_I18N_LOCALE", (String) session.get("language_code"));
		}

		System.out.println(session.get("WW_TRANS_I18N_LOCALE"));
		System.out.println(invocation.getInvocationContext().getLocale().getCountry());
		return result;
	}



}
